<?php
namespace hacklog\doctohtml;

use yii\base\Component;
use Yii;

class DocToHtml extends Component
{
    public $libreoffice_path = '/usr/bin/soffice';

    public $pdf2htmlex_path = '/usr/bin/pdf2htmlEX';

    public $tmp_dir = '/tmp/doc2html';

    /**
     * 用途：
     * @param $info
     * @return string
     * @author 李猛
     */
    public function convert($filename){
        if (!is_dir($this->tmp_dir)) {
            mkdir($this->tmp_dir, 0777);
        }
        $cur_tmp_dir = $this->tmp_dir . DIRECTORY_SEPARATOR . md5($filename);
        @rmdir($cur_tmp_dir);
        exec(sprintf("rm -rf %s", escapeshellarg($cur_tmp_dir)));
        mkdir($cur_tmp_dir, 0777);

        $ext = pathinfo($filename, PATHINFO_EXTENSION);

        $savePath = '';
        $output_name =date("YmdHis").rand(1000,9999)."_new.html";
        switch ($ext){
            case "xlsx":
            case "xls":
                $base= $cur_tmp_dir;
                $fileType= \PhpOffice\PhpSpreadsheet\IOFactory::identify($filename);
                $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($filename);
                $savePath = $base . DIRECTORY_SEPARATOR . $output_name; //这里记得将文件名包含进去
                $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($objPHPExcel);
                $writer->setSheetIndex(0);
                $writer->save($savePath);
                return $savePath;
                break;
            case "doc":
            case "docx":
                $base= $cur_tmp_dir;
                $cmd= $this->libreoffice_path . ' --headless --convert-to html --outdir '.$base;
                $cmd.=" ".$filename;
                setlocale(LC_ALL, 'en-us.UTF-8');
                $savePath = $base . DIRECTORY_SEPARATOR . str_replace($ext, 'html', basename($filename));
                break;
            case "pdf":
                //pdf2htmlEX [options] <input.pdf> [<output.html>]
                $base= $cur_tmp_dir;
                $cmd= $this->pdf2htmlex_path . " --embed-image 0 --embed-external-font 0 --optimize-text 0 --dest-dir ";
                $cmd.=$base." ".$filename." ".$output_name;
                $savePath = $base . DIRECTORY_SEPARATOR . $output_name;
                break;
            default:
                $cmd='';
                throw new \Exception("extension $ext is not allowed!\n");
                break;
        }
        $rs = exec($cmd,$output,$ret);
        if ($ret !== 0) {
            $out = trim(implode(', ', $output));
            throw new \Exception("exec $cmd failed. ouput: $out\n");
        }
        return $savePath;
    }
}